package com.wzh.himalaya.presenters;

import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_RANDOM;
import static com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP;

import android.content.Context;
import android.content.SharedPreferences;

import com.wzh.himalaya.base.BaseApplication;
import com.wzh.himalaya.interfaces.IPlayerCallBack;
import com.wzh.himalaya.interfaces.IPlayerPresenter;
import com.wzh.himalaya.utils.LogUtil;
import com.ximalaya.ting.android.opensdk.model.PlayableModel;
import com.ximalaya.ting.android.opensdk.model.advertis.Advertis;
import com.ximalaya.ting.android.opensdk.model.advertis.AdvertisList;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager;
import com.ximalaya.ting.android.opensdk.player.advertis.IXmAdsStatusListener;
import com.ximalaya.ting.android.opensdk.player.constants.PlayerConstants;
import com.ximalaya.ting.android.opensdk.player.service.IXmPlayerStatusListener;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayerException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.RecursiveTask;

/**
 * className:PlayerPresenter
 * Author:WZH
 * Time:2022-04-12
 */
public class PlayerPresenter implements IPlayerPresenter, IXmAdsStatusListener, IXmPlayerStatusListener {


    private final SharedPreferences mPlayModeSp;
    private List<IPlayerCallBack> mIPlayerCallBacks = new ArrayList<>();

    private static final String TAG = "PlayerPresenter";
    private final XmPlayerManager mPlayerManager;
    private Track mCurrentTrack;
    private int mCurrentIndex=0;
    private XmPlayListControl.PlayMode mCurrentPlayMode = PLAY_MODEL_LIST;
    private boolean mIsReverse=false;

/*  PLAY_MODEL_LIST
    PLAY_MODEL_LIST_LOOP
    PLAY_MODEL_RANDOM
    PLAY_MODEL_SINGLE_LOOP
*/

    public static final int PLAY_MODE_LIST_INT=0;
    public static final int PLAY_MODEL_LIST_LOOP_INT=1;
    public static final int PLAY_MODEL_RANDOM_INT=2;
    public static final int PLAY_MODEL_SINGLE_LOOP_INT=3;

    //sp's key and name
    public static  final String PLAY_MODE_SP_NAME="PlayMode";
    public static  final String PLAY_MODE_SP_KEY="currentPlayMode";
    private PlayerPresenter(){
        mPlayerManager = XmPlayerManager.getInstance(BaseApplication.getAppContext());
        //广告物料相关的注册
        mPlayerManager.addAdsStatusListener(this);
        //注册播放器状态相关的接口
        mPlayerManager.addPlayerStatusListener(this);
        //需要记录当前的播放模式  （使用sp来存储数据）
        mPlayModeSp = BaseApplication.getAppContext().getSharedPreferences(PLAY_MODE_SP_NAME, Context.MODE_PRIVATE);
    }


    private  static  PlayerPresenter sPlayerPresenter;

    public static PlayerPresenter getPlayerPresenter() {
        if (sPlayerPresenter == null) {
            synchronized (PlayerPresenter.class) {
                if (sPlayerPresenter == null) {
                    sPlayerPresenter = new PlayerPresenter();
                }
            }
        }
        return sPlayerPresenter;
    }


    private boolean isPlayListSet = false;
    public void setPlayList(List<Track> list,int playIndex){
        if (mPlayerManager != null) {
            mPlayerManager.setPlayList(list, playIndex);
            isPlayListSet=true;
            //这里是第一次进入播放的时候 拿到标题 然后要去设置
            mCurrentTrack = list.get(playIndex);
            mCurrentIndex = playIndex;

         //   mTrackTitle = mTrack.getTrackTitle();
        }else{
            LogUtil.d(TAG,"mPlayerManager is null");
        }
    }







    @Override
    public void play() {
        if(isPlayListSet){
            mPlayerManager.play();
        }
    }

    @Override
    public void pause() {
        if(mPlayerManager!=null){
            mPlayerManager.pause();
        }
    }

    @Override
    public void stop() {

    }


    @Override
    public void playPre() {
        //别忘记边界处理
        if (mPlayerManager != null) {
            mPlayerManager.playPre();
        }
    }

    @Override
    public void playNext() {
        if (mPlayerManager != null) {
            mPlayerManager.playNext();
        }
    }

    @Override
    public void switchPlayMode(XmPlayListControl.PlayMode mode) {
        if (mPlayerManager != null) {
            mCurrentPlayMode = mode;
            mPlayerManager.setPlayMode(mode);
            for (IPlayerCallBack iPlayerCallBack : mIPlayerCallBacks) {
                iPlayerCallBack.onPlayModeChange(mode);
            }
            //保存到sp里面去
            SharedPreferences.Editor edit = mPlayModeSp.edit();
            edit.putInt(PLAY_MODE_SP_KEY,getIntByPlayMode(mode));
            edit.commit();
        }

    }

    //这个是为了转一下数据类型吧
    private int getIntByPlayMode(XmPlayListControl.PlayMode mode){
        switch (mode){
            case PLAY_MODEL_SINGLE_LOOP:
                return PLAY_MODEL_SINGLE_LOOP_INT;
            case PLAY_MODEL_LIST_LOOP:
                return PLAY_MODEL_LIST_LOOP_INT;
            case PLAY_MODEL_RANDOM:
                return PLAY_MODEL_RANDOM_INT;
            case PLAY_MODEL_LIST:
                return PLAY_MODE_LIST_INT;



        }
        return PLAY_MODE_LIST_INT;
    }


    private XmPlayListControl.PlayMode getModeByInt(int index){
        switch (index){
            case PLAY_MODEL_SINGLE_LOOP_INT:
                return PLAY_MODEL_SINGLE_LOOP;
            case PLAY_MODEL_LIST_LOOP_INT:
                return PLAY_MODEL_LIST_LOOP;
            case PLAY_MODEL_RANDOM_INT:
                return PLAY_MODEL_RANDOM;
            case PLAY_MODE_LIST_INT:
                return PLAY_MODEL_LIST;



        }
        return PLAY_MODEL_LIST;
    }

    @Override
    public void getPlayList() {
        if (mPlayerManager != null) {
            List<Track> playList =   mPlayerManager.getPlayList();
            for (IPlayerCallBack iPlayerCallBack : mIPlayerCallBacks) {
                iPlayerCallBack.onListLoaded(playList);
            }
        }
    }

    @Override
    public void playByIndex(int index) {
        //切换播放器到第index个位置进行播放
        if (mPlayerManager != null) {
            mPlayerManager.play(index);
        }
    }

    @Override
    public void seekTo(int progress) {
        //更新播放器的进度
        mPlayerManager.seekTo(progress);
    }

    //返回当前是否正在播放
    @Override
    public boolean isPlay() {
        return mPlayerManager.isPlaying();
    }



    @Override
    public void reversePlayList() {


        //把播放列表反转
        List<Track> playList = mPlayerManager.getPlayList();
        Collections.reverse(playList);
        mIsReverse=!mIsReverse;
        //新下标= size-1-当前下标
        mCurrentIndex = playList.size()-1-mCurrentIndex;
        mPlayerManager.setPlayList(playList,mCurrentIndex);
        //更新ui
        mCurrentTrack = (Track) mPlayerManager.getCurrSound();
        for (IPlayerCallBack iPlayerCallBack : mIPlayerCallBacks) {
            iPlayerCallBack.onListLoaded(playList);
            iPlayerCallBack.onTrackUpdate(mCurrentTrack,mCurrentIndex);
            iPlayerCallBack.updateListOrder(mIsReverse);
        }
    }




    @Override
    public void registerViewCallback(IPlayerCallBack iPlayerCallBack) {

        //第一次进如详情的时候去设置标题
        iPlayerCallBack.onTrackUpdate(mCurrentTrack,mCurrentIndex);
        //从sp里拿
        int modeIndex = mPlayModeSp.getInt(PLAY_MODE_SP_KEY,PLAY_MODE_LIST_INT);
        mCurrentPlayMode = getModeByInt(modeIndex);


        iPlayerCallBack.onPlayModeChange(mCurrentPlayMode);

        if (!mIPlayerCallBacks.contains(iPlayerCallBack)) {
            mIPlayerCallBacks.add(iPlayerCallBack);
        }
    }


    @Override
    public void unregisterViewCallback(IPlayerCallBack iPlayerCallBack) {
        mIPlayerCallBacks.remove(iPlayerCallBack);
    }



    //广告相关的回调方法========================== start
    @Override
    public void onStartGetAdsInfo() {
        LogUtil.d(TAG,"onStartGetAdsInfo   `````````");
    }

    @Override
    public void onGetAdsInfo(AdvertisList advertisList) {
        LogUtil.d(TAG,"onGetAdsInfo````````````");
    }

    @Override
    public void onAdsStartBuffering() {
        LogUtil.d(TAG,"onAdsStartBuffering``````````````");
    }

    @Override
    public void onAdsStopBuffering() {
        LogUtil.d(TAG,"onAdsStopBuffering````````````");

    }

    @Override
    public void onStartPlayAds(Advertis advertis, int i) {
        LogUtil.d(TAG,"onStartPlayAds```````````````````");

    }

    @Override
    public void onCompletePlayAds() {
        LogUtil.d(TAG,"onCompletePlayAds`````````````````");
    }

    @Override
    public void onError(int what, int extra) {
        LogUtil.d(TAG,"onError what is"+what+"    extra is"+extra);
    }

    //========================广告相关的回调方法============= end



    //===============播放器相关的回调方法========================start
    @Override
    public void onPlayStart() {
        LogUtil.d(TAG,"开始播放··········");
        for (IPlayerCallBack iPlayerCallBack : mIPlayerCallBacks) {
            iPlayerCallBack.onPlayStart();
        }
    }

    @Override
    public void onPlayPause() {
        LogUtil.d(TAG,"暂停播放··········");
        for (IPlayerCallBack iPlayerCallBack : mIPlayerCallBacks) {
            iPlayerCallBack.onPlayPause();
        }
    }

    @Override
    public void onPlayStop() {
        LogUtil.d(TAG,"停止播放···········");
        for (IPlayerCallBack iPlayerCallBack : mIPlayerCallBacks) {
            iPlayerCallBack.onPlayStop();
        }
    }

    @Override
    public void onSoundPlayComplete() {
        LogUtil.d(TAG,"播放完成---------");
    }

    @Override
    public void onSoundPrepared() {
        LogUtil.d(TAG,"播放器准备完毕-------");
        mPlayerManager.setPlayMode(mCurrentPlayMode);
        //原本在activity里面的.play 放到这里来 等待播放器准备完毕后 再去播放音频
        if (mPlayerManager.getPlayerStatus()== PlayerConstants.STATE_PREPARED) {
            //播放器准备完毕
            mPlayerManager.play();
        }

    }

    @Override
    public void onSoundSwitch(PlayableModel lastModel, PlayableModel curModel) {
        //  .getKind() 获取类型
        //第一种写法 不推荐
//        if ("track".equals(curModel.getKind())) {
//            Track currentTrack = (Track) curModel;
//            LogUtil.d(TAG,"title----->"+currentTrack.getTrackTitle());
//        }

        //使用第二种写法
        mCurrentIndex = mPlayerManager.getCurrentIndex();

        if(curModel instanceof Track){
            Track currentTrack = (Track) curModel;
            mCurrentTrack  = currentTrack;
            //更新UI
            for (IPlayerCallBack iPlayerCallBack : mIPlayerCallBacks) {
                iPlayerCallBack.onTrackUpdate(mCurrentTrack,mCurrentIndex);
            }
        }


    }

    @Override
    public void onBufferingStart() {
        LogUtil.d(TAG,"缓冲开始--------");
    }

    @Override
    public void onBufferingStop() {
        LogUtil.d(TAG,"缓冲完成·········");
    }

    @Override
    public void onBufferProgress(int progress) {
        LogUtil.d(TAG,"缓冲进度-----"+progress);
    }

    @Override
    public void onPlayProgress(int currPos, int duration) {
        //单位是毫秒
        for (IPlayerCallBack iPlayerCallBack : mIPlayerCallBacks) {
            iPlayerCallBack.onProgressChange(currPos,duration);
        }


    }

    @Override
    public boolean onError(XmPlayerException e) {
        LogUtil.d(TAG,"onError exception------>"+e);
        return false;
    }

    //===============播放器相关的回调方法========================end
}
